package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

//方法一：递归一
/*
func reversePrint(head *ListNode)[]int{
	if head == nil{
		return nil
	}
	return appendData(head)
}

func appendData(head *ListNode)[]int{
	if head.Next != nil{
		NodeList := appendData(head.Next)
		NodeList = append(NodeList, head.Val)
		return NodeList
	}
	return []int{head.Val}
}
*/

/*
方法二：递归二
func reversePrint(head *ListNode) *ListNode {
   if head == nil || head.Next == nil{
       return head
   }
   newHead := reverseList(head.Next)
   head.Next.Next = head
   head.Next = nil
   return newHead
}
*/

//方法三：反转链表打印
/*
func reversePrint(head *ListNode)[]int{
	if head == nil{
		return nil
	}
	var newHead *ListNode
	var res []int
	for head != nil{
	node := head.Next
	head.Next = newHead
	newHead = head
	head = node
	}
	for newHead != nil{
		res = append(res,newHead.Val)
		newHead = newHead.Next
	}
	return res
}
*/

//方法四：借助栈
func reversePrint(head *ListNode) []int {
	if head == nil {
		return nil
	}
	var list []int
	var res []int
	for head != nil {
		list = append(list, head.Val)
		head = head.Next
	}
	Len := len(list)
	for i := Len - 1; i >= 0; i-- {
		res = append(res, list[i])
	}
	return res
}

//AddNode 从末尾添加元素
func AddNode(head *ListNode, data *ListNode) {
	temp := head
	for {
		if temp.Next == nil {
			break
		}
		temp = temp.Next
	}
	temp.Next = data
}

//ShowNode 显示全部链表
func ShowNode(head *ListNode) {
	temp := head
	//判断是否为空
	if temp.Next == nil {
		fmt.Println("error:node is nil")
		return
	}
	//遍历链表
	for {
		fmt.Printf("%v", temp.Val)
		temp = temp.Next
		if temp.Next == nil {
			break
		}
	}
}

func main() {
	//创造头节点
	head := &ListNode{}
	//创造新元素
	n1 := &ListNode{
		Val: 2,
	}
	n2 := &ListNode{
		Val: 4,
	}
	n3 := &ListNode{
		Val: 1,
	}

	//加入
	AddNode(head, n1)
	AddNode(head, n2)
	AddNode(head, n3)
	// //显示
	// ShowNode(head)
	fmt.Println(reversePrint(n1))
}
